package lottery;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author jarryxu
 * @version 1.0
 * @title LotteryService.java
 * @package lottery
 * @date 2022/5/14 16:17
 * @description
 */
public class LotteryService {
    /**
     * 奖品池
     */
    public static String[] prizes = {"代金券10元","代金券50元","蓝牙耳机","Switch游戏机","iPhone 13Pro","谢谢参与"};
    /**
     * 奖品和中奖率映射
     */
    public static Map<Integer/*奖品序号*/,Integer/*中奖概率*/> mapping;

    // 初始化各个奖品中奖率（单位为%），加起来等于100
    static {
        mapping = new HashMap<>();
        // 20%
        mapping.put(0,20);
        // 14%
        mapping.put(1,14);
        // 10%
        mapping.put(2,10);
        // 5%
        mapping.put(3,5);
        // 1%
        mapping.put(4,1);
        // 50%
        mapping.put(5,50);
    }

    /**
     * 抽奖
     * @return 奖品序号
     */
    public static Integer doLottery() {
        // 生成0到100的随机数
        double i = Math.floor(Math.random() * 100);
        System.out.println("随机数:" + i);

        // 生成奖品中奖区间
        int[] tmp = new int[prizes.length];
        int cur = 0;
        int j = 0;
        for (Map.Entry<Integer, Integer> entry : mapping.entrySet()) {
            cur += entry.getValue();
            tmp[j] = cur;
            j++;
        }

        // 根据随机数是否在中奖区间判断抽中的奖品
        for (int i1 = 0; i1 < tmp.length; i1++) {
            if (i <= tmp[i1]) {
                return i1;
            }
        }

        // 默认返回"谢谢参与"
        return 5;
    }

    public static void main(String[] args) {
        // 抽奖次数
        int c = 1000;
        Map<Integer,Integer> countMap = new HashMap<>();
        for (int i = 0; i < c; i++) {
            Integer s = doLottery();
            System.out.println("抽到的奖品:" + prizes[s]);

            if (countMap.containsKey(s)) {
                Integer integer = countMap.get(s);
                countMap.put(s,++integer);
            } else {
                countMap.put(s,1);
            }
        }

        System.out.println("--------------------");

        // 统计综合中奖率
        for (int i = 0; i < prizes.length; i++) {
            System.out.println(prizes[i] + " 中奖次数:" + countMap.get(i) + ",中奖率:" + BigDecimal.valueOf(countMap.get(i))
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(c),1, RoundingMode.FLOOR));
        }
    }
}